import { ref } from 'vue'
import { defineStore } from 'pinia'

import api from '@/api/student'
import type { StudentInfo } from '@/config/types'
import type { StudentInfoForm } from '@/config/form'

export const useStudentStore = defineStore('student', () => {
  const loading = ref<boolean>(false)
  const studentInfo = ref<StudentInfo>({
    name: '',
    username: '',
    nickname: '',
    avatar: '',
    phone: '',
    email: '',
    gender: '',
    birthday: '',
    address: '',
    hobby: ''
  })

  async function getInfo() {
    loading.value = true
    try {
      const res = await api.info()
      studentInfo.value = res.data
    } finally {
      loading.value = false
    }
  }

  async function updateInfo(form: StudentInfoForm) {
    loading.value = true
    let result: boolean
    try {
      const res = await api.update(form)
      result = res.data
    } catch (e) {
      result = false
    } finally {
      loading.value = false
    }
    return result
  }

  return {
    loading,
    studentInfo,

    getInfo,
    updateInfo
  }
})
